<template>
  <div class="admin-registration-entries">
    <!-- 面包屑导航 -->
    <Breadcrumb />
    
    <div class="page-header">
      <h1>报名入口管理</h1>
      <p>管理院校报名入口信息</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="学校名称">
          <el-input v-model="searchForm.schoolName" placeholder="请输入学校名称" clearable />
        </el-form-item>
        <el-form-item label="年度">
          <el-select v-model="searchForm.year" placeholder="选择年度" clearable>
            <el-option :value="2025" label="2025年" />
            <el-option :value="2024" label="2024年" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadEntries">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>报名入口列表</span>
          <div>
            <el-button type="primary" @click="addEntry">添加入口</el-button>
            <el-button 
              type="danger" 
              :disabled="selectedIds.length === 0"
              @click="batchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        v-loading="loading" 
        :data="entries" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="schoolName" label="学校名称" min-width="200" />
        <el-table-column prop="registrationStartTime" label="报名开始时间" width="150" />
        <el-table-column prop="registrationEndTime" label="报名结束时间" width="150" />
        <el-table-column prop="registrationUrl" label="报名链接" min-width="200">
          <template #default="{ row }">
            <el-link 
              v-if="row.registrationUrl" 
              :href="row.registrationUrl" 
              type="primary" 
              target="_blank"
            >
              {{ row.registrationUrl.length > 50 ? row.registrationUrl.substring(0, 50) + '...' : row.registrationUrl }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="year" label="年度" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editEntry(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteEntry(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadEntries"
          @current-change="loadEntries"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加报名入口' : '编辑报名入口'" 
      width="600px"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules" 
        label-width="120px"
      >
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="form.schoolName" placeholder="请输入学校名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名开始时间" prop="registrationStartTime">
              <el-input v-model="form.registrationStartTime" placeholder="如：3月1日" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名结束时间" prop="registrationEndTime">
              <el-input v-model="form.registrationEndTime" placeholder="如：4月10日" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="报名链接" prop="registrationUrl">
          <el-input 
            v-model="form.registrationUrl" 
            placeholder="请输入报名链接"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年度" prop="year">
              <el-select v-model="form.year" placeholder="选择年度">
                <el-option :value="2025" label="2025年" />
                <el-option :value="2024" label="2024年" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="选择状态">
                <el-option :value="1" label="启用" />
                <el-option :value="0" label="禁用" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="备注信息（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitForm">
          {{ submitting ? '提交中...' : '确定' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Breadcrumb from '@/components/Breadcrumb.vue'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const entries = ref([])
const selectedIds = ref([])

const searchForm = reactive({
  schoolName: '',
  year: null,
  status: null
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const dialogVisible = ref(false)
const dialogMode = ref('add')
const formRef = ref()

const form = reactive({
  id: null,
  schoolName: '',
  schoolId: null,
  registrationStartTime: '',
  registrationEndTime: '',
  registrationUrl: '',
  status: 1,
  year: 2025,
  remark: '',
  sortOrder: 0
})

const formRules = {
  schoolName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  registrationStartTime: [
    { required: true, message: '请输入报名开始时间', trigger: 'blur' }
  ],
  registrationEndTime: [
    { required: true, message: '请输入报名结束时间', trigger: 'blur' }
  ],
  registrationUrl: [
    { required: true, message: '请输入报名链接', trigger: 'blur' }
  ],
  year: [
    { required: true, message: '请选择年度', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 方法
const loadEntries = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    const { data } = await api.get('/admin/registration-entries', { params })
    entries.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    schoolName: '',
    year: null,
    status: null
  })
  pagination.page = 1
  loadEntries()
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const addEntry = () => {
  dialogMode.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const editEntry = (row) => {
  dialogMode.value = 'edit'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    schoolName: '',
    schoolId: null,
    registrationStartTime: '',
    registrationEndTime: '',
    registrationUrl: '',
    status: 1,
    year: 2025,
    remark: '',
    sortOrder: 0
  })
  formRef.value?.clearValidate()
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogMode.value === 'add') {
      await api.post('/admin/registration-entries', form)
      ElMessage.success('添加成功')
    } else {
      await api.put(`/admin/registration-entries/${form.id}`, form)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadEntries()
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const deleteEntry = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个报名入口吗？', '确认删除', {
      type: 'warning'
    })
    
    await api.delete(`/admin/registration-entries/${row.id}`)
    ElMessage.success('删除成功')
    loadEntries()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要批量删除选中的报名入口吗？', '确认删除', {
      type: 'warning'
    })
    
    await api.post('/admin/registration-entries/batch/delete', selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    loadEntries()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  loadEntries()
})
</script>

<style lang="scss" scoped>
.admin-registration-entries {
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style>